<?php
// +----------------------------------------------------------------------
// | YotakuCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.yotaku.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Creatint <creatint@163.com> 
// +----------------------------------------------------------------------

namespace Home\Controller;

use Common\Tool\Zip;

/**
 * 文档模型控制器
 * 文档模型列表和详情
 */
class AgentController extends HomeController {

    public function _initialize()
    {
        parent::_initialize();
        if ( USER_TYPE !== 'agent' || session('user_auth.uid') != 3) {
            $this->error('未登录或无权限，请重新确认登陆身份！',U('User/logout'));
        } else {
            trace('agent权限正常', '权限情况');
        }

        // 获取dashboard数据
        $dashboard['quota'] = D('UcenterMember')->sum('quota');
        $dashboard['used'] = D('UcenterMember')->sum('used');
        $dashboard['price'] = D('Record')->where(['status'=>['in',[1]]])->sum('price');
        $dashboard['price'] = round($dashboard['price'],2);
        $this->assign('dashboard',$dashboard);
    }

    /* 导出表格数据 */
	public function export(){
		import('Org.Util.PHPExcel');
		$row = C('ROW');
		$this->assign('controller','Agent');
		$this->assign('action','export');

		$PHPExcel = new \PHPExcel();
		$PHPExcel
			->getProperties()  //获得文件属性对象，给下文提供设置资源
			->setCreator( session('user_auth.username'))                 //设置文件的创建者
			->setLastModifiedBy( session('user_auth.username') )          //设置最后修改者
			->setTitle( "Office 2007 XLSX Test Document" )    //设置标题
			->setSubject( "Office 2007 XLSX Test Document" )  //设置主题
			->setDescription( "Test document for Office 2007 XLSX, generated using PHP classes.") //设置备注
			->setKeywords( "office 2007 openxml php")        //设置标记
			->setCategory( "Test result file");                //设置类别
		// 位置aaa  *为下文代码位置提供锚
		// 给表格添加数据
		$PHPExcel->setActiveSheetIndex(0)             //设置第一个内置表（一个xls文件里可以有多个表）为活动的
			->setCellValue( 'A1', 'NO.' )
			->setCellValue( 'B1', '车牌号' )
			->setCellValue( 'C1', '经销商代码' )
			->setCellValue( 'D1', '创建时间' )
			->setCellValue( 'E1', '审核时间' )
			->setCellValue( 'F1', '审核状态' )
            ->setCellValue( 'G1', '车型' )
			->setCellValue( 'H1', '轮胎品牌' )
			->setCellValue( 'I1', '备件号' )
            ->setCellValue( 'J1', '补贴金额' );

		// 经销商数据
        $dealers = D('UcenterMember')->getField('id,id,username');

		$status_arr = [
		    0=>'未审核',
            1=>'通过',
            2=>'未通过',
            3=>'已删除'
        ];

        // 记录文档模型
        $Record = D('Record');
        //是否搜索g
        $query = ['status'=>['in',[0,1,2,3]]];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        // 获取记录列表
        $list = $Record->lists($query, 0, 0);
		$i = 2;
//		dump($list);exit;

//        echo count($list);
 //       exit;
		foreach($list as $v){
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("A{$i}",$v['id']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("B{$i}",$v['plate_number']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("C{$i}",$dealers[$v['user_id']]['username']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("D{$i}",date('Y-m-d H:i:s', $v['created_at']));
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("E{$i}",$v['checked_at']>0?date('Y-m-d H:i:s', $v['checked_at']):'-');
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("F{$i}",$status_arr[$v['status']]);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("G{$i}",$v['car']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("H{$i}",$v['tyre_brand']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("I{$i}",$v['tyre_number']);
			$PHPExcel->setActiveSheetIndex(0)->setCellValue("J{$i}",$v['status']==1?$v['price']:0);
			$i++;
		}



		//得到当前活动的表,注意下文教程中会经常用到$objActSheet
		$objActSheet = $PHPExcel->getActiveSheet();
		// 位置bbb  *为下文代码位置提供锚
		// 给当前活动的表设置名称
		$objActSheet->setTitle('记录_'.time());

		//直接生成一个文件
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="记录_'.date('Ymd_H_i_s',time()).'.xls"');
		header('Cache-Control: max-age=0');
		$objWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel5');
		$objWriter->save('php://output');

		// 生成2003excel格式的xls文件
//		header('Content-Type: application/vnd.ms-excel');
//		header('Content-Disposition: attachment;filename="01simple.xls"');
//		header('Cache-Control: max-age=0');
//
//		$objWriter = PHPExcel_IOFactory::createWriter($PHPExcel, 'Excel5');
//		$objWriter->save('php://output');
//		exit;




	}


    // 导出图片数据
    public function exportImg(){

	    // 获取所有用户
        $dealers = D('UcenterMember')->getField('id,username');

	    // 获取所有记录
        $Record = D('Record');
        $query = ['status'=>['in',[0,1,2,3]]];
        $records = $Record->where($query)->field('user_id,images')->select();

        // 获取所有图片记录
        $images_row = D('Picture')->getField('id,id,path,create_time');

        // 图片列表
        $images_user = [];
        foreach( $records as $key => $value ) {
            $value['images'] = preg_split('/[,]+/',trim($value['images'],','));
            foreach( $value['images'] as $k => $v ) {
                $images_user[(int)$v] = $dealers[(int)$value['user_id']];
            }
        }

        // 文件夹名与目标压缩文件名
        $folder_name = './Uploads/Download/' . date('Y-m-d',time());
        $folder_zip = './Uploads/Download/images.zip';
//        $folder_zip = './Uploads/Download/' . date('Y-m-d_H-i-s',time()) . '.' . 'zip';

//        $pattern = '/^.*\/([0-9a-zA-Z\.]*)$/i';
        $pattern = '/^.*\/([0-9a-zA-Z]*)\.([a-zA-Z]*)$/i';

        foreach( $images_row as &$img ) {
        	$img['dealer'] = $images_user[$img['id']]?$images_user[$img['id']]:'0';
        	preg_match($pattern, $img['path'], $matches);
        	$img['name'] = $matches[1].'.'.$matches[2];
        	$img['newName'] = $folder_name . '/' . $img['dealer'] . '_' . date('Y-m-d_H-i-s',$img['create_time']). '.' . $matches[2];
        	$img['path'] = '.' . $img['path'];
        	$img['newPath'] = $folder_name . '/' . $img['name'];
        }unset($img);

//        dump($images_row);

        // 建立文件夹
//        dump($folder_name);
        mkdirs($folder_name);

        // 移动文件
        copys( $images_row,'path','newPath' );

        // 重命名文件
        renames( $images_row, 'newPath', 'newName');

        Zip::zipDir($folder_name,$folder_zip);

        if ( file_exists($folder_zip) ) {
            $handle = fopen($folder_zip,'r');
            header('Location: /Uploads/Download/images.zip');
            die;
        } else {
            $this->error('压缩文件失败');
        }


    }



    /* 文档模型频道页 */
	public function index(){
		$row = C('ROW');
		$this->assign('controller','Agent');
		$this->assign('action','index');

        // 记录文档模型
        $Record = D('Record');

        //是否搜索g
        $query = ['status'=>['in',[1,2]]];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        // 获取记录列表
        $p = !empty($_GET['p'])?$_GET['p']:1;
        $list = $Record->lists($query, $p, C('ROW'));
        $count = $Record->listCount($query);
        $start = $count - ($p - 1) * C('ROW');
        foreach($list as &$v) {
            $v['no'] = $start;
            $start--;
        }

        //分页
        $this->assign('row',C('ROW'));
        $page = new \Common\Tool\Page($count, C('ROW'));
        $page->setConfig('them','');
        $this->assign('_page',$page->show());
        $this->assign('list',$list);
        $this->display();


	}


    /* 文档模型频道页 */
    public function delete(){
        $row = C('ROW');
        $this->assign('controller','Agent');
        $this->assign('action','delete');

        // 记录文档模型
        $Record = D('Record');

        //是否搜索
        $query = ['status'=>3];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        // 获取记录列表
        $p = !empty($_GET['p'])?$_GET['p']:1;
        $list = $Record->lists($query, $p, C('ROW'));
        $count = $Record->listCount($query);
        $start = $count - ($p - 1) * C('ROW');
        foreach($list as &$v) {
            $v['no'] = $start;
            $start--;
        }
        //分页
        $this->assign('row',C('ROW'));
        $page = new \Common\Tool\Page($count, C('ROW'));
        $page->setConfig('them','');
        $this->assign('_page',$page->show());
        $this->assign('list',$list);
        $this->display();


    }


	/* 审核记录 */
	public function check(){
		$this->assign('controller','Agent');
		$this->assign('action','check');

        // 记录文档模型
        $Record = D('Record');

        // 限制条件
        $query = ['status'=>0];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        // 获取记录列表
        $list = $Record->lists($query,!empty($_GET['p'])?$_GET['p']:1, C('ROW'), '`created_at` ASC');

        //分页
        $this->assign('row',C('ROW'));
        $page = new \Common\Tool\Page($Record->listCount($query), C('ROW'));
        $page->setConfig('them','');
        $this->assign('_page',$page->show());
        $this->assign('list',$list);
        $this->assign('causes', C('CAUSE'));


		$this->display();
	}


    /**
     * 经销商管理.
     *
     */
	public function dealermanage(){

		$row = C('ROW');
		$this->assign('controller','Agent');
		$this->assign('action','dealermanage');




        // 限制条件
        $query = [];
        // 获取查询条件
        $query = add_search($query, I('get.'));
        $query['group_id'] = 1;
        // 获取记录列表
		$list = D('UcenterMember')->lists($query,!empty($_GET['p'])?$_GET['p']:1,$row,'`quota` DESC',true);
		// 计算补贴金额
        foreach ( $list as &$v ) {
            $v['price'] = round(D('Record')->where(['user_id'=>$v['id'],'status'=>['in',[1]]])->sum('price'),2);
        }
		$this->assign('list',$list);

		//分页
		$this->assign('row',$row);
		$page = new \Common\Tool\Page(D('UcenterMember')->listCount($query), $row);
		$page->setConfig('them','');
		$this->assign('_page',$page->show());


		$this->display();
	}



	// api方法
	public function api(){
	    $res = array();
	    if ( $_POST['action'] == 'addQuota' ) {
	        if ( !(I('post.id',0)>0) ) {
	            $res['status'] = 0;
	            $res['msg'] = 'E020';
	            goto a;
            }
	        // 修改剩余配额
            // 原数据
            $data = D('UcenterMember')->where('id='.I('post.id'))->field("quota,used")->find();
            if ( I('post.quota',0) >= $data['used'] ) {
                if ( D('UcenterMember')->update($_POST['id'],['quota'=>$_POST['quota']]) ){
                    $res['data'] = D('UcenterMember')->where('id='.I('post.id'))->field("quota,used")->find();
                    $res['status'] = 1;
                    $res['msg'] = '修改成功';
                } else {
                    $res['status'] = 0;
                    $res['msg'] = '修改失败 '. D('UcenterMember')->getError();
                }
            } else {
                // 无法减少总配额
                $res['status'] = 0;
                $res['msg'] = '已用的配额为 '.$data['used']. ',无法减少总配额';
                $res['data'] = $data;
            }

            a:

            $this->ajaxReturn($res);
        }elseif($_GET['action'] == 'check'){
	        // 审核原因
            $cause = I('cause','');
	        // 审核记录
            if ( !$_GET['id']>0 ) {
                $this->error('无记录ID',U('Agent/check'));
            } else {
                $Record = D('Record');
                if ( $Record->where("id={$_GET['id']}")->save(['status'=>(int)$_GET['status'],'checked_at'=>time(),'cause'=>$cause]) ) {
                    // 回复经销商配额
                    $record = $Record->find($_GET['id']);
                    // 判断status，1:通过审核，2:不通过审核，3:删除操作
                    // 删除时恢复经销商的配额
                    if ( $_GET['status'] == 3 ) {
                        if ( D('UcenterMember')->where(['id'=>$record['user_id']])->setDec('used',$record['number']) ) {
                            $this->success('操作成功');
                        } else {
                            $this->error('恢复经销商配额可能失败 '.D('UcenterMember')->getError());
                        }
                    } else {
                        $this->success('操作成功');
                    }
                } else {
                    $this->error('操作失败 '.$Record->getError());
                }
            }
        }elseif($_GET['action'] == 'delete'){
            // 删除记录
            if ( !$_GET['id']>0 ) {
                $this->error('无记录ID',U('Agent/check'));
            } else {
                $Record = D('Record');
                if ( $Record->where("id={$_GET['id']}")->save(['status'=>(int)$_GET['status'],'checked_at'=>time()]) ) {
                    // 回复经销商配额
                    $record = $Record->find($_GET['id']);
                    // 判断status，1:通过审核，2:不通过审核，3:删除操作
                    // 删除时恢复经销商的配额
                    if ( $_GET['status'] == 3 ) {
                        if ( D('UcenterMember')->where(['id'=>$record['user_id']])->setDec('used',$record['number']) ) {
                            $this->success('操作成功');
                        } else {
                            $this->error('恢复经销商配额可能失败 '.D('UcenterMember')->getError());
                        }
                    } else {
                        $this->success('操作成功');
                    }
                } else {
                    $this->error('操作失败 '.$Record->getError());
                }
            }
        } elseif ($_POST['action'] == 'getQuota'){
            $res['status'] = 1;
            $res['msg'] = 'ddd';
            $res['data'] = D('UcenterMember')->where('id='.I('post.uid'))->field("quota,used")->find();
            $res['data']['quota'] = D('UcenterMember')->sum('quota');
            $res['data']['used'] = D('UcenterMember')->sum('used');
            $res['data']['price'] = D('Record')->where(['status'=>['in',[1]]])->sum('price');
            $res['data']['price'] = round($res['data']['price'],2);
            $this->ajaxReturn($res);
        }




    }

}
